package com.java110.mall.cart.bmo.goldBusiness.impl;

import com.alibaba.fastjson.JSONObject;
import com.java110.dto.user.StoreStaffDto;
import com.java110.intf.user.IStoreStaffV1InnerServiceSMO;
import com.java110.mall.cart.bmo.goldBusiness.ISaveGoldBusinessBMO;
import com.java110.core.annotation.Java110Transactional;
import com.java110.core.factory.GenerateCodeFactory;
import com.java110.dto.account.AccountDto;
import com.java110.dto.account.AccountDetailDto;
import com.java110.dto.coupon.CouponPoolDto;
import com.java110.dto.coupon.CouponShopPoolDto;
import com.java110.dto.gold.GoldBusinessDto;
import com.java110.dto.shop.ShopDto;
import com.java110.dto.user.UserDto;
import com.java110.intf.acct.*;
import com.java110.intf.cart.IGoldBusinessInnerServiceSMO;
import com.java110.intf.shop.IShopInnerServiceSMO;
import com.java110.intf.user.IStoreV1InnerServiceSMO;
import com.java110.intf.user.IUserV1InnerServiceSMO;
import com.java110.po.account.AccountDetailPo;
import com.java110.po.account.AccountPo;
import com.java110.po.coupon.CouponDetailPo;
import com.java110.po.coupon.CouponPoolPo;
import com.java110.po.coupon.CouponShopPoolPo;
import com.java110.po.gold.GoldBusinessPo;
import com.java110.utils.lock.DistributedLock;
import com.java110.utils.util.Assert;
import com.java110.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

@Service("saveGoldBusinessBMOImpl")
public class SaveGoldBusinessBMOImpl implements ISaveGoldBusinessBMO {

    @Autowired
    private IGoldBusinessInnerServiceSMO goldBusinessInnerServiceSMOImpl;

    @Autowired
    private IUserV1InnerServiceSMO userInnerServiceSMOImpl;

    @Autowired
    private IStoreV1InnerServiceSMO storeInnerServiceSMOImpl;

    @Autowired
    private IAccountDetailInnerServiceSMO accountDetailInnerServiceSMOImpl;

    @Autowired
    private IAccountInnerServiceSMO accountInnerServiceSMOImpl;
    @Autowired
    private ICouponPoolV1InnerServiceSMO couponPoolV1InnerServiceSMOImpl;

    @Autowired
    private ICouponDetailV1InnerServiceSMO couponDetailV1InnerServiceSMOImpl;
    @Autowired
    private ICouponShopPoolV1InnerServiceSMO couponShopPoolV1InnerServiceSMOImpl;

    @Autowired
    private ICouponShopPoolDetailV1InnerServiceSMO couponShopPoolDetailV1InnerServiceSMOImpl;
    @Autowired
    private IShopInnerServiceSMO shopInnerServiceSMOImpl;

    @Autowired
    private IStoreStaffV1InnerServiceSMO storeStaffV1InnerServiceSMOImpl;

    public static final String CODE_PREFIX_ID = "10";
    /**
     * 添加小区信息
     *
     * @param goldBusinessPo
     * @return 订单服务能够接受的报文
     */
    @Java110Transactional
    public ResponseEntity<String> save(GoldBusinessPo goldBusinessPo) {

        goldBusinessPo.setBusiId(GenerateCodeFactory.getGeneratorId("11"));
        int flag = goldBusinessInnerServiceSMOImpl.saveGoldBusiness(goldBusinessPo);

        if (flag > 0) {
            return ResultVo.createResponseEntity(ResultVo.CODE_OK, "保存成功");
        }

        return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "保存失败");
    }

    /**
     * 购买金币
     * goldObj.put("orderId", orderId);
     * goldObj.put("buyPrice", buyPrice);
     * goldObj.put("goldCount", goldCount);
     * goldObj.put("userId", pd.getUserId());
     *
     * @param reqJson
     * @return
     */
    @Override
    @Java110Transactional
    public ResponseEntity<String> buy(JSONObject reqJson) {

        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);

        Assert.listOnlyOne(userDtos, "用户信息错误");

        //查询商户信息
        StoreStaffDto storeStaffDto = new StoreStaffDto();
        storeStaffDto.setStaffId(userDtos.get(0).getUserId());
        List<StoreStaffDto> storeUserDtos =  storeStaffV1InnerServiceSMOImpl.queryStoreStaffs(storeStaffDto);
        Assert.listOnlyOne(storeUserDtos, "商户信息错误");


        //添加金币购买记录
        GoldBusinessPo goldBusinessPo = new GoldBusinessPo();
        goldBusinessPo.setAmount(reqJson.getString("buyPrice"));
        goldBusinessPo.setBusiId(GenerateCodeFactory.getGeneratorId("11"));
        goldBusinessPo.setBusiType(GoldBusinessDto.BUSI_TYPE_BUY);
        goldBusinessPo.setBuyerId(reqJson.getString("userId"));
        goldBusinessPo.setBuyerName(userDtos.get(0).getName());
        goldBusinessPo.setGoldCount(reqJson.getString("goldCount"));
        goldBusinessPo.setGoldType(GoldBusinessDto.GOLD_TYPE_PUBLIC);
        goldBusinessPo.setStoreId(storeUserDtos.get(0).getStoreId());
        goldBusinessPo.setStoreName(storeUserDtos.get(0).getName());
        goldBusinessPo.setRemark("购买金币");
        int flag = goldBusinessInnerServiceSMOImpl.saveGoldBusiness(goldBusinessPo);

        if (flag < 1) {
            throw new IllegalArgumentException("添加金币购买记录失败");
        }
        //查询金币账户

        AccountDto accountDto = new AccountDto();
        accountDto.setObjId(storeUserDtos.get(0).getStoreId());
        accountDto.setAcctType(AccountDto.ACCT_TYPE_CASH);
        List<AccountDto> accountDtos = accountInnerServiceSMOImpl.queryAccounts(accountDto);

        Assert.listOnlyOne(accountDtos, "账户异常");
        //添加入账户明细
        AccountDetailPo accountDetailPo = new AccountDetailPo();
        accountDetailPo.setAcctId(accountDtos.get(0).getAcctId());
        accountDetailPo.setAmount(reqJson.getString("buyPrice"));
        accountDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(GenerateCodeFactory.CODE_PREFIX_detailId));
        accountDetailPo.setDetailType(AccountDetailDto.DETAIL_TYPE_IN);
        accountDetailPo.setObjId(accountDtos.get(0).getObjId());
        accountDetailPo.setObjType(accountDtos.get(0).getObjType());
        accountDetailPo.setOrderId(reqJson.getString("orderId"));
        accountDetailPo.setRelAcctId("-1");
        accountDetailPo.setRemark("购买金币");
        flag = accountDetailInnerServiceSMOImpl.saveAccountDetails(accountDetailPo);
        if (flag < 1) {
            throw new IllegalArgumentException("添加账户明细失败");
        }
        //
        String requestId = DistributedLock.getLockUUID();
        String key = accountDtos.get(0).getAcctId();
        try {
            DistributedLock.waitGetDistributedLock(key, requestId);
            accountDto = new AccountDto();
            accountDto.setObjId(storeUserDtos.get(0).getStoreId());
            accountDto.setAcctId(accountDtos.get(0).getAcctId());
            accountDtos = accountInnerServiceSMOImpl.queryAccounts(accountDto);
            //在积分账户增加
            double amount = Double.parseDouble(accountDtos.get(0).getAmount());
            BigDecimal amountBig = new BigDecimal(amount);
            amount = amountBig.add(new BigDecimal(reqJson.getDouble("buyPrice"))).doubleValue();
            AccountPo accountPo = new AccountPo();
            accountPo.setObjId(accountDtos.get(0).getObjId());
            accountPo.setAcctId(accountDtos.get(0).getObjId());
            accountPo.setAmount(amount + "");
            flag = accountInnerServiceSMOImpl.updateAccount(accountPo);
            if (flag < 1) {
                throw new IllegalArgumentException("添加账户明细失败");
            }
        } finally {
            DistributedLock.releaseDistributedLock(requestId, key);
        }

        return ResultVo.success();
    }

    /**
     * 购买金币
     * goldObj.put("orderId", orderId);
     * goldObj.put("shopId", shopId);
     * goldObj.put("poolId", poolId);
     * goldObj.put("buyPrice", buyPrice);
     * goldObj.put("goldCount", goldCount);
     * goldObj.put("userId", pd.getUserId());
     *
     * @param reqJson
     * @return
     */
    @Override
    @Java110Transactional
    public ResponseEntity<String> coupon(JSONObject reqJson) {

        UserDto userDto = new UserDto();
        userDto.setUserId(reqJson.getString("userId"));
        List<UserDto> userDtos = userInnerServiceSMOImpl.queryUsers(userDto);
        Assert.listOnlyOne(userDtos, "用户信息错误");

        double buyPrice = reqJson.getDouble("buyPrice"); //支付金额
        BigDecimal goldCount = new BigDecimal(reqJson.getDouble("goldCount")); //购买数量
        String poolId = reqJson.getString("poolId"); //购物券ID
        String shopId = reqJson.getString("shopId"); //商铺ID
        String orderId = reqJson.getString("orderId"); //订单ID
        ShopDto shopDto = new ShopDto();
        shopDto.setShopId(shopId);
        List<ShopDto> shopDtos = shopInnerServiceSMOImpl.queryShops(shopDto);
        Assert.listOnlyOne(shopDtos, "未查询到购物券信息，请联系管理员");

        CouponPoolDto couponPoolDto = new CouponPoolDto();
        couponPoolDto.setPoolId(poolId);
        List<CouponPoolDto> couponPoolDtos = couponPoolV1InnerServiceSMOImpl.queryCouponPools(couponPoolDto);
        Assert.listOnlyOne(couponPoolDtos, "未查询到购物券信息，请联系管理员");
        //修改库存
        BigDecimal couponStock = new BigDecimal(couponPoolDtos.get(0).getCouponStock());
        couponStock = couponStock.subtract(goldCount).setScale(2, BigDecimal.ROUND_HALF_EVEN);
        if (couponStock.compareTo(BigDecimal.ZERO) < 0) {
            return ResultVo.createResponseEntity(ResultVo.CODE_ERROR, "库存不够请联系管理员，请联系管理员");
        }
        CouponPoolPo couponPoolPo = new CouponPoolPo();
        couponPoolPo.setPoolId(couponPoolDtos.get(0).getPoolId());
        couponPoolPo.setCouponStock(couponStock.doubleValue() + "");
        int flag = couponPoolV1InnerServiceSMOImpl.updateCouponPool(couponPoolPo);
        if (flag < 1) {
            throw new IllegalArgumentException("添加金币购买记录失败");
        }

        //添加买出购买记录
        CouponDetailPo couponDetailPo = new CouponDetailPo();
        couponDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        couponDetailPo.setCouponName(couponPoolDtos.get(0).getCouponName());
        couponDetailPo.setAmount(buyPrice+"");
        couponDetailPo.setShopId(shopId);
        couponDetailPo.setOrderId(orderId);
        couponDetailPo.setPoolId(poolId);
        couponDetailPo.setBuyCount(goldCount.doubleValue()+"");
        couponDetailPo.setActualPrice(couponPoolDtos.get(0).getActualPrice());
        couponDetailPo.setValidityDay(couponPoolDtos.get(0).getValidityDay());
        couponDetailPo.setBuyPrice(couponPoolDtos.get(0).getBuyPrice());
        couponDetailPo.setShopName(shopDtos.get(0).getShopName());
        flag = couponDetailV1InnerServiceSMOImpl.saveCouponDetail(couponDetailPo);

        if (flag < 1) {
            throw new IllegalArgumentException("添加买出购买记录失败");
        }
        //添加店铺优惠券
        CouponShopPoolPo couponShopPoolPo = new CouponShopPoolPo();

        CouponShopPoolDto couponShopPoolDto = new CouponShopPoolDto();
        couponShopPoolDto.setPoolId(poolId);
        couponShopPoolDto.setShopId(shopId);
        List<CouponShopPoolDto>  couponShopPoolDtos = couponShopPoolV1InnerServiceSMOImpl.queryCouponShopPools(couponShopPoolDto);
        if(couponShopPoolDtos != null && couponShopPoolDtos.size() > 0){
            //修改库存
            BigDecimal stock = new BigDecimal(couponShopPoolDtos.get(0).getStock());
            BigDecimal  newStock = stock.add(goldCount).setScale(2, BigDecimal.ROUND_HALF_EVEN);
            couponShopPoolPo.setSpId(couponShopPoolDtos.get(0).getSpId());
            couponShopPoolPo.setStock(newStock.doubleValue()+"");
            flag = couponShopPoolV1InnerServiceSMOImpl.updateCouponShopPool(couponShopPoolPo);
            if (flag < 1) {
                throw new IllegalArgumentException("完善店铺优惠券库存失败");
            }
            return ResultVo.success();
        }

        couponShopPoolPo.setSpId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
        couponShopPoolPo.setStock(goldCount.doubleValue()+"");
        couponShopPoolPo.setValidityDay(couponPoolDtos.get(0).getValidityDay());

        couponShopPoolPo.setCouponName(couponPoolDtos.get(0).getCouponName());
        couponShopPoolPo.setShopId(shopId);
        couponShopPoolPo.setPoolId(poolId);
        couponShopPoolPo.setActualPrice(couponPoolDtos.get(0).getActualPrice());
        flag = couponShopPoolV1InnerServiceSMOImpl.saveCouponShopPool(couponShopPoolPo);
        if (flag < 1) {
            throw new IllegalArgumentException("添加店铺优惠券失败");
        }
//        //添加店铺买入
//        CouponShopPoolDetailPo couponShopPoolDetailPo = new CouponShopPoolDetailPo();
//        couponShopPoolDetailPo.setDetailId(GenerateCodeFactory.getGeneratorId(CODE_PREFIX_ID));
//        couponShopPoolDetailPo.setCouponName(couponPoolDtos.get(0).getCouponName());
//        couponShopPoolDetailPo.setShopId(shopId);
//        couponShopPoolDetailPo.setPoolId(poolId);
//        couponShopPoolDetailPo.setOrderId(orderId);
//        couponShopPoolDetailPo.setActualPrice(couponPoolDtos.get(0).getActualPrice());
//        couponShopPoolDetailPo.setSendCount("0");
//        couponShopPoolDetailPo.setValidityDay(couponPoolDtos.get(0).getValidityDay());
//        couponShopPoolDetailPo.setSpId(couponShopPoolPo.getSpId());
//        couponShopPoolDetailV1InnerServiceSMO.saveCouponShopPoolDetail(couponShopPoolDetailPo);

        return ResultVo.success();
    }

}
